package fi.iki.joker.mobilogger;

import java.util.LinkedList;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.Spinner;
import fi.iki.joker.mobilogger.db.DBConstants;
import fi.iki.joker.mobilogger.util.SettingHelper;

/**
 * This activity is the box that appears when user is appending an image to the posting. It's not currently
 * working yet. The underlying assumption here is that we have three types of images that user may append to
 * posting:
 * URL - images which we can reference in a posting by means of simple URL
 * local - images which are on device and need to be uploaded somewhere
 * web - images which are already in web but the URL needs to be generated by means of an external API
 * (like picasa)
 * Each type of image is handled separately.
 * @author juhak
 *
 */

public class ImageSelectionActivity extends Activity implements 
	AdapterView.OnItemSelectedListener {

	private final String TAG = "ImageSelectionActivity";
	private LinkedList<String> selectables = null;
	private SettingHelper settingHelper = null;
	private int picasaStatus;
	private enum IMG_SOURCE_STATE {STATE_URL,STATE_LOCAL, STATE_WEB};
	private IMG_SOURCE_STATE currentState = IMG_SOURCE_STATE.STATE_URL;
	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
		}
	};
	private ProgressDialog picasaCommsProgress = null;
	final Runnable fetchResults = new Runnable() {
		public void run () {
				showFetchStatus();
		}
	};
	
	public static class UrlText extends EditText {
        private Rect mRect;
        private Paint mPaint;

        // we need this constructor for ViewInflate
        public UrlText(Context context, AttributeSet attrs, Map params) {
            super(context, attrs, params);

            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
        }
        public UrlText(Context context) {
            super(context);

            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
        }
	}
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.imageselection);
		settingHelper = new SettingHelper();
		Spinner imageSrcSpinner = (Spinner)findViewById(R.id.imgsourcespinner);
		// when activity is first created, hide the gallery and imageswitcher,
		// and show the edittext. When user changes the state of the spinner,
		// these are shown according to the selection
		Gallery gallery = (Gallery)findViewById(R.id.gallery);
		ImageSwitcher imageSwitcher = (ImageSwitcher)findViewById(R.id.imageswitcher);
		Button picasaButton = (Button)findViewById(R.id.fetchpicasadatabutton);
		Button imageSelectionOkButton = (Button)findViewById(R.id.imageselectionokbutton);
		gallery.setVisibility(View.GONE);
		imageSwitcher.setVisibility(View.GONE); 
		picasaButton.setVisibility(View.GONE);
		picasaButton.setText("Fetch Your Albums");
		picasaButton.setOnClickListener(picasaFetchListener);
		imageSelectionOkButton.setOnClickListener(commitSelectionListener);
		selectables = new LinkedList<String>();
		selectables.add("Image from URL");
		selectables.add("Image from memory");
		selectables.add("Image from Web ("+settingHelper.getSettingValue(DBConstants.SETTING_KEY_IMAGELIB)+")");
		Object res = new ArrayAdapter(this,android.R.layout.simple_spinner_item,selectables);
		ArrayAdapter<CharSequence> adapter = (ArrayAdapter<CharSequence>)res;
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		imageSrcSpinner.setAdapter(adapter);
		imageSrcSpinner.setOnItemSelectedListener(this);
		// at the beginning we are on the URL selection state.
		currentState = IMG_SOURCE_STATE.STATE_URL;
	}

	public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
		EditText imageUrlText = (EditText)findViewById(R.id.imageurltext);
		Gallery gallery = (Gallery)findViewById(R.id.gallery);
		ImageSwitcher imageSwitcher = (ImageSwitcher)findViewById(R.id.imageswitcher);
		Button picasaButton = (Button)findViewById(R.id.fetchpicasadatabutton);
		if(arg2 == 0) {
			// show url text field, gone others
			gallery.setVisibility(View.GONE);
			imageSwitcher.setVisibility(View.GONE);
			imageUrlText.setVisibility(View.VISIBLE);
			picasaButton.setVisibility(View.GONE);
			currentState = IMG_SOURCE_STATE.STATE_URL;
		} else if(arg2 == 1) {
			// gone url text field, show others
			gallery.setVisibility(View.VISIBLE);
			imageSwitcher.setVisibility(View.VISIBLE);
			imageUrlText.setVisibility(View.GONE);
			picasaButton.setVisibility(View.GONE);
			currentState = IMG_SOURCE_STATE.STATE_LOCAL;
			showAlert("Notice",0,"For now, only URL-embedding works. The other options are still a work-in-progress (see MobiLogger release plan).","OK",false);
		} else if(arg2 == 2) {
			// gone url text field, show others
			gallery.setVisibility(View.GONE);
			imageSwitcher.setVisibility(View.GONE);
			imageUrlText.setVisibility(View.GONE);
			picasaButton.setVisibility(View.VISIBLE);
			currentState = IMG_SOURCE_STATE.STATE_WEB;
			showAlert("Notice",0,"For now, only URL-embedding works. The other options are still a work-in-progress (see MobiLogger release plan).","OK",false);
		}
	}

	public void onNothingSelected(AdapterView arg0) {
		// TODO Auto-generated method stub
		currentState = IMG_SOURCE_STATE.STATE_URL;
	}

	OnClickListener picasaFetchListener = new OnClickListener() {
		public void onClick(View v) {
			showAlert("Picasa integration note",0,
					"Picasa integration is pending due to technical problems.",
					"OK",false);
			/* not implemented
			Thread picasaFetch = new Thread () {
				public void run() {
					mHandler.getLooper().prepare();
					Message statusMsg = mHandler.obtainMessage();
					picasaStatus = 0;
					status.put(MSG_KEY, "1");
					statusMsg.setData(status);
					mHandler.sendMessage(statusMsg);
					PicasaWebUtil pwu = new PicasaWebUtil();
					List<PicasaWebUtil.SimpleAlbumTO> user_albums =
					null;//pwu.getUserAlbums("juha.kervinen@gmail.com");
					Iterator<PicasaWebUtil.SimpleAlbumTO> iter = user_albums.iterator();
					while(iter.hasNext()) {
						Log.d(TAG,"Album: "+iter.next().getName());
					}
					mHandler.post(fetchResults);
				}
			};	
			picasaFetch.start();*/
		}
	};
	
	private void showFetchStatus() {
		
	}
	
	OnClickListener commitSelectionListener = new OnClickListener() {
		public void onClick(View v) {
			//based on the selection source state, send different message
			//to memo editor activity
			switch(currentState) {
			case STATE_URL:
				EditText imgUrlText = (EditText)findViewById(R.id.imageurltext);
				String data = imgUrlText.getText().toString();
				if(data == null || data.length()==0) {
					showAlert("Check your input",0,"The image URL is empty!","Ok",false);
					return;
				} else {
					setResult(RESULT_OK, data);
					finish();
				}
				break;
			case STATE_LOCAL:
				break;
			case STATE_WEB:
				break;
			}
		}
	};

	
}
